<!--
 * @Author: your name
 * @Date: 2021-12-06 19:38:26
 * @LastEditTime: 2022-03-06 11:33:48
 * @LastEditors: your name
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \soldier\src\components\Upload\upload.vue
-->
<template>
  <div>
    <el-form label-width="120px" :model="dataForm" class="dialog-form" label-position="right">
      <el-form-item label="上传文件">
        <el-upload ref="upload" drag accept=".jpg, .png" name="file" :auto-upload="false" :limit="10"
          :http-request="httpRequest" :action="apiUrl" :before-upload="beforeUpload" :on-success="uploadSuccess"
          :file-list="dataForm.file" :on-error="uploadError">
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doUpload">确定</el-button>
    </div>
  </div>
</template>

<script>
import { insertWuziFile } from '@/api/wuzi'
export default {
  props: {
    apiUrl: {
      type: String,
      default: '',
    },
    rowid: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      headers: {
        token: localStorage.getItem('token') || '',
        'content-Type': 'multipart/form-data'
      },
      dataForm: {}
    }
  },
  methods: {
    beforeUpload(file) {

      if (!this.$util.validFile(file, 'png')) {
        this.$message({
          message: '上传文件格式不正确!',
          type: 'error',
        })
        return false
      }
      if (file.size / 1024 / 1024 > 200) {
        this.$message({
          message: '上传文件大小不能超过200MB!',
          type: 'error',
        })
        return false
      }
      return true
    },
    httpRequest(param) {

      this.dataForm.file = param.file
    },
    uploadSuccess(res) {
      if (res.code == 200) {
        this.$message({
          message: '导入成功',
          type: 'success',
        })
        this.$emit('success')
      } else {
        this.$message({
          message: res.message,
          type: 'error',
        })
      }
    },
    uploadError(e) {
      this.$message({
        message: '上传失败，请按照指定的模板格式进行上传',
        type: 'error',
      })
    },
    async doUpload() {
      this.$refs.upload.submit()

      this.dataForm.wuziid = this.rowid
      let data = await insertWuziFile(this.dataForm)
      if (data.code == 200) {
        this.$message({
          message: '导入成功',
          type: 'success',
        })
        this.$emit('success')
      } else {
        this.$message({
          message: res.message,
          type: 'error',
        })
      }
    },
  },
}
</script>

<style></style>
